package com.nf.health.app.datamain.fragment;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.datamain.activity.BloodOxygenActivity;
import com.nf.health.app.datamain.activity.BloodPressureActivity;
import com.nf.health.app.datamain.activity.BloodSugarDataActivity;
import com.nf.health.app.fragment.IBaseFragment;
import com.nf.health.app.healthstate.activity.HealthStateActivity;
import com.nf.health.app.datamain.activity.HealthyBraceletActivity;
import com.nf.health.app.datamain.activity.MeasureHeartRateActivity;
import com.nf.health.app.datamain.activity.TemperatureDataActivity;
import com.nf.health.app.datamain.activity.UrineTestActivity;
import com.nf.health.app.activity.ecg.EcgHistoryActivity;
import com.nf.health.app.adapter.MainDataAdapter;
import com.nf.health.app.bodyfat.BodyFatDataNewActivity;
import com.nf.health.app.customview.HpCircleGradeProgress;
import com.nf.health.app.models.DeviceData;
import com.nf.health.app.models.HealthStateBean;
import com.nf.health.app.sweat.activity.PreSweatAnalyzerActivity;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

@SuppressLint("NewApi")
public class MainDataFragment extends IBaseFragment {


    @Bind(R.id.titlebar_title_tv)
    TextView titlebarTitleTv;
    HpCircleGradeProgress ivCircleProgress;
    @Bind(R.id.listview)
    ListView listview;
    @Bind(R.id.titlebar_back_view)
    ImageView titlebarBackView;
    @Bind(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.ll_container)
    LinearLayout ll_container;
    TextView tvHealthPercent;
    TextView tvAbnormal;
    TextView health_text;

    private List<DeviceData> deviceDatas = new ArrayList<>();
    private MainDataAdapter adapter;

    private static final String REQUEST_HEALTH_STATE = "request_health_state";

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addViewFillInRoot(R.layout.fragment_maindata);
        ButterKnife.bind(this, rootView);
        titlebarBackView.setVisibility(View.GONE);
        initView();
        initListener();

    }

    private void initListener() {
        listview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //头布局点击不处理
                if (position == 0) {
                    //跳到健康状态
                    ActivityUtils.showActivity(getActivity(), HealthStateActivity.class);
                    return;
                }
                if (deviceDatas != null) {
                    if (!Util.checkBluetoothAvailable()){
                        showToast("手机不支持蓝牙4.3");
                        return;
                    }
                    String type = deviceDatas.get(position - 1).getDeviceType();
                    Bundle bundle = new Bundle();
                    bundle.putString("deviceType", type);
                    if (DeviceData.Type.BALANCE.equals(type)) {
                        //跳到体脂数据
                        ActivityUtils.showActivity(getActivity(), BodyFatDataNewActivity.class, bundle); //新的体脂测量界面
                    } else if (DeviceData.Type.BLOOD_SUGAR.equals(type)) {
                        //跳到血糖数据
                        ActivityUtils.showActivity(getActivity(), BloodSugarDataActivity.class, bundle);
                    } else if (DeviceData.Type.BLOOD_PRESSURE.equals(type)) {
                        //跳到血压数据
                        ActivityUtils.showActivity(getActivity(), BloodPressureActivity.class, bundle);
                    } else if (DeviceData.Type.BRACELET.equals(type)) {
                        //跳到手环数据
                        ActivityUtils.showActivity(getActivity(), HealthyBraceletActivity.class, bundle);
                    } else if (DeviceData.Type.URINE.equals(type)) {
                        //跳到尿检数据
                        ActivityUtils.showActivity(getActivity(), UrineTestActivity.class, bundle);
                    } else if (DeviceData.Type.SWEAT.equals(type)) {
                        //跳到汗液仪数据
//                        ActivityUtils.showActivity(getActivity(), SweatAnalyzerActivity.class, bundle);
                        ActivityUtils.showActivity(getActivity(), PreSweatAnalyzerActivity.class, bundle);
                    } else if (DeviceData.Type.TEMPERATURE.equals(type)) {
                        //跳到体温数据
                        ActivityUtils.showActivity(getActivity(), TemperatureDataActivity.class, bundle);
                    } else if (DeviceData.Type.OXYGEN.equals(type)) {
                        //跳到血氧数据
                        ActivityUtils.showActivity(getActivity(), BloodOxygenActivity.class, bundle);
                    } else if (DeviceData.Type.ECG.equals(type)) {
                        //跳到心电数据
                        ActivityUtils.showActivity(getActivity(), EcgHistoryActivity.class);
                    } else if (DeviceData.Type.HEART_RATE.equals(type)) {
                        //跳到心率数据
                        ActivityUtils.showActivity(getActivity(), MeasureHeartRateActivity.class);
                    }
                }
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                provider.requestGetData("refreshData");
                provider.requestHealthState(REQUEST_HEALTH_STATE);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        provider.requestGetData("refreshData");
        provider.requestHealthState(REQUEST_HEALTH_STATE);
    }

    private void initView() {
        View rootView = View.inflate(getActivity(), R.layout.item_main_data_header, null);
        titlebarTitleTv.setText("健康数据");

        tvHealthPercent = ViewUtil.getView(rootView, R.id.tv_health_percent);
        tvAbnormal = ViewUtil.getView(rootView, R.id.tv_abnormal);
        health_text = ViewUtil.getView(rootView, R.id.health_text);
        ivCircleProgress = ViewUtil.getView(rootView, R.id.iv_circle_progress);
        listview.addHeaderView(rootView);
        swipeRefreshLayout.setColorSchemeResources(R.color.theme_color, android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_orange_light);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            int statusBarHeight = ScreentUtils.getStatusBarHeight(getActivity().getBaseContext());
            ll_container.setPadding(0, statusBarHeight, 0, 0);
            Window window = getActivity().getWindow();
        }
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        super.handleActionFinish(actionName, object);
        if(swipeRefreshLayout == null){
            return ;
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if ("refreshData".equals(actionName)) {
            swipeRefreshLayout.setRefreshing(false);
            List<DeviceData> datas = (List<DeviceData>) object;
            deviceDatas.clear();
            deviceDatas.addAll(datas);
            if (adapter == null) {
                adapter = new MainDataAdapter(getActivity(), deviceDatas);
                listview.setAdapter(adapter);
            } else {
                adapter.notifyDataSetChanged();
            }
        } else if (REQUEST_HEALTH_STATE.equals(actionName)) {
            swipeRefreshLayout.setRefreshing(false);
            HealthStateBean bean = (HealthStateBean) object;
            tvHealthPercent.setText(bean.getScore() + "%");
            tvAbnormal.setText(bean.getFail() + "项指标存在异常!");
            health_text.setText(bean.getHealth());

//            ivCircleProgress.setProgress(Float.valueOf(bean.getScore()));
            setProgress(ivCircleProgress, Float.valueOf(bean.getScore()));
        }
    }

    /**
     * 设置progress 用子线程完成动画效果
     *
     * @param view
     * @param target
     */
    private void setProgress(final HpCircleGradeProgress view, final float target) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                SystemClock.sleep(500);
                int progress = 0;
                while (progress <= target) {
                    view.setProgress(progress);
                    progress++;
                    SystemClock.sleep(10);
                }
            }
        }).start();
    }
}